//
//  DAPersonalSettingViewController.m
//  DAKnowledge
//
//  Created by DreamArts on 16/4/28.
//  Copyright © 2016年 lidongyang. All rights reserved.
//

#import "DAPersonalSettingViewController.h"
#import "Utility.h"
#import "DAPersonalSettingTableViewCell.h"
#import "DAAlertView.h"
//#import "MBProgressHUD.h"
#import "SVProgressHUD.h"
#import "DAUserProfile.h"
#import "DAloginPersonalInformation.h"
#import "DAChangeWordController.h"
#import "DAChangePassWordViewController.h"
#import "DACollectedFilesViewController.h"
@interface DAPersonalSettingViewController ()<UITableViewDataSource, UITableViewDelegate,changeWordDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) NSArray *sectionOneTitleArray;
@property (nonatomic, strong) NSArray *sectionTwoTitleArray;
@property (nonatomic, strong) NSArray *sectionThreeTitleArray;
//@property (nonatomic, strong) MBProgressHUD *hud;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) DAUserProfile *userModel;
@property (nonatomic, strong) DAloginPersonalInformation *personalInformation;
@end

@implementation DAPersonalSettingViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.translucent = NO;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    /**  隐藏导航栏 */
    self.navigationController.navigationBarHidden = NO;
    /** 调用tableViewSetting 方法*/
    [self tableViewSetting];
    /** 调用数据准备*/
    [self prepareData];
}
#pragma mark - tableView
- (void)tableViewSetting{
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor themeWhiteColor];
}
#pragma mark - 数据准备
- (void)prepareData{
    NSString *nickName = NSLocalizedString(@"nickName", nil);
    NSString *sign = NSLocalizedString(@"personalSign", nil);
    NSString *changePassWordStr = NSLocalizedString(@"changePassWord", nil);
    NSString *version = NSLocalizedString(@"Version", nil);
    NSString *cleanCache = NSLocalizedString(@"cleanCache", nil);
    NSString *logOut = NSLocalizedString(@"logOut", nil);
    NSString *collectedFiles = NSLocalizedString(@"collectedFiles", nil);
    
    self.sectionOneTitleArray = @[nickName, sign, changePassWordStr];
    self.sectionTwoTitleArray = @[version, cleanCache, logOut];
    self.sectionThreeTitleArray = @[collectedFiles];
    /** 解档*/
    NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES).lastObject stringByAppendingString:@"DALogin"];
    self.personalInformation = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];

}
#pragma mark - tableView dataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return self.sectionOneTitleArray.count;
    }else if (section == 1){
        return self.sectionTwoTitleArray.count;
    }else{
        return self.sectionThreeTitleArray.count;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    DAPersonalSettingTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (indexPath.section == 0) {
        cell.titleLabel.text = self.sectionOneTitleArray[indexPath.row];
        if (indexPath.row == 0) {
            if (![self.personalInformation.userName isKindOfClass:[NSNull class]]) {
                cell.contentLabel.text = self.personalInformation.userName;
                cell.contentLabel.textColor = [UIColor colorWithHexString:@"#A0A0A0"];
            }
        }else if (indexPath.row == 1){
            if (![self.personalInformation.userSign isKindOfClass:[NSNull class]]) {
                cell.contentLabel.text = self.personalInformation.userSign;
                cell.contentLabel.textColor = [UIColor colorWithHexString:@"#A0A0A0"];
            }
        }else{
            cell.rightImage.image = [UIImage imageNamed:@"rightArrow"];
        }
        cell.selectionStyle = NO;
      
    }
    if (indexPath.section == 1) {
        cell.titleLabel.text = self.sectionTwoTitleArray[indexPath.row];
        cell.rightImage.image = nil;
        if (indexPath.row == 0) {
            cell.contentLabel.text = [[[NSBundle mainBundle]infoDictionary]valueForKey:@"CFBundleShortVersionString"];
            cell.contentLabel.textAlignment = NSTextAlignmentRight;
        }else if (indexPath.row == 1){
            cell.contentLabel.text = [self returnCachesStr];
        }
        cell.contentLabel.textColor = [UIColor colorWithHexString:@"#A0A0A0"];
        cell.selectionStyle = NO;
    }
    if (indexPath.section == 2) {
        cell.titleLabel.text = self.sectionThreeTitleArray[indexPath.row];
        cell.selectionStyle = NO;
    }
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 20;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.1;
}
#pragma mark - tableView点击方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0){
        if(indexPath.row == 2){
            DAChangePassWordViewController *changePassWord = [[DAChangePassWordViewController alloc]init];
            [self.navigationController pushViewController:changePassWord animated:YES];
            return;
        }
        DAChangeWordController *changeVC = [[DAChangeWordController alloc]init];
        changeVC.delegate = self;
        if(indexPath.row == 0){
            changeVC.oldString = self.personalInformation.userName;
            changeVC.anotherString = self.personalInformation.userSign;
            changeVC.changeWordType = ChangeWordTypeName;
        }else if (indexPath.row == 1){
            changeVC.oldString = self.personalInformation.userSign;
            changeVC.anotherString = self.personalInformation.userName;
            changeVC.changeWordType = ChangeWordTypeSign;
        }
        [self.navigationController pushViewController:changeVC animated:YES];
    }
    if (indexPath.section == 1 && indexPath.row == 2) {
        NSLog(@"注销");
        NSString *logoutStr = NSLocalizedString(@"SureToExitTheCurrentNumber", nil);
        NSString *suerStr = NSLocalizedString(@"Sure", nil);
        NSString *cancelStr = NSLocalizedString(@"cancel", nil);
        NSString *hint = NSLocalizedString(@"hint", nil);
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:hint message:logoutStr preferredStyle:UIAlertControllerStyleActionSheet];
        UIAlertAction *topAction = [UIAlertAction actionWithTitle:suerStr style: UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            /** 退出*/
            [self logout];
        }];
        UIAlertAction *bottomAction = [UIAlertAction actionWithTitle:cancelStr style:UIAlertActionStyleCancel handler:nil];
        [alert addAction:topAction];
        [alert addAction:bottomAction];
        [self presentViewController:alert animated:YES completion:nil];
    }
    if (indexPath.section == 1 && indexPath.row == 1) {
        
        NSString *clearStr = NSLocalizedString(@"SureyouWantToClearTheCache", nil);
        NSString *suerStr = NSLocalizedString(@"Sure", nil);
        NSString *cancelStr = NSLocalizedString(@"cancel", nil);
        NSString *hint = NSLocalizedString(@"hint", nil);
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:hint message:clearStr preferredStyle:UIAlertControllerStyleActionSheet];
        UIAlertAction *leftAction = [UIAlertAction actionWithTitle:suerStr style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            // 清除文件夹缓存
            [self removeCache];
            [self.tableView reloadData];
        }];
        UIAlertAction *rightAction = [UIAlertAction actionWithTitle:cancelStr style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        }];
        [alert addAction:leftAction];
        [alert addAction:rightAction];
        [self presentViewController:alert animated:YES completion:nil];
    }
    if (indexPath.section == 2) {
        DACollectedFilesViewController *collectFile = [self.storyboard instantiateViewControllerWithIdentifier:@"ColectedFilesController"];
        [self.navigationController pushViewController:collectFile animated:YES];
    }
}
#pragma mark - 获取缓存文件大小
- (NSString *)returnCachesStr{
    NSString *cachesPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
    NSString *str = [NSString stringWithFormat:@"%.2fM",[self floatWithPath:cachesPath]];

    return str;
}
#pragma mark - 获取到本地文件路径
- (NSString *)getFielPath{
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"userProfile"];
    return path;
}
#pragma mark - 根据文件夹路径删除文件 并回到登录页面
- (void)logout{
    /** 调用菊花*/
    NSString *isLogout = NSLocalizedString(@"isLogoutNow", nil);
     [SVProgressHUD showWithStatus:isLogout];
    /** 根据文件夹路径 删除文件*/
    NSFileManager *manger = [NSFileManager defaultManager];
    [manger removeItemAtPath:[self getFielPath] error:nil];
    // 删除缓存
    [self removeCache];
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setBool:NO forKey:@"isLogin"];
    [userDefaults setBool:NO forKey:@"isArichiveData"];
    [self goBackLoginPage];
    // 把lastReplyID 设为 0 当清除缓存的时候
    [userDefaults setObject:@"0" forKey:@"lastReplyID"];
    // 清除消息缓存
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingString:@"Message"];
    NSFileManager *fileManager = [[NSFileManager alloc]init];
    [fileManager removeItemAtPath:path error:nil];
    
}
// 计算清除的缓存大小
- (CGFloat)floatWithPath:(NSString *)path{
    CGFloat num = 0;
    NSFileManager *man = [NSFileManager defaultManager];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];

    if ([man fileExistsAtPath:path]) {
        NSEnumerator *childFile = [[man subpathsAtPath:path] objectEnumerator];
        NSString *fileName;
        while ((fileName = [childFile nextObject]) != nil) {
            NSString *fileSub = [path stringByAppendingPathComponent:fileName];
            num += [self fileSizeAtPath:fileSub];
        }
    }
    
    if([man fileExistsAtPath:documentsDirectory]){
        NSEnumerator *childFile = [[man subpathsAtPath:documentsDirectory] objectEnumerator];
        NSString *fileName;
        while ((fileName = [childFile nextObject]) != nil) {
            NSString *fileSub = [documentsDirectory stringByAppendingPathComponent:fileName];
            num += [self fileSizeAtPath:fileSub];
        }
    }
    return num / (1024.0 * 1024.0);
}
//计算单个文件大小
- (long long)fileSizeAtPath:(NSString *)file{
    NSFileManager *man = [NSFileManager defaultManager];
    if ([man fileExistsAtPath:file]) {
        return [[man attributesOfItemAtPath:file error:nil] fileSize];
    }
    return 0;
}
// 删除缓存
- (void)removeCache {
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachePath];
    NSArray *uploadFiles = [[NSFileManager defaultManager] subpathsAtPath:documentsDirectory];
    for (NSString *p in files) {
        NSString * path = [NSString stringWithFormat:@"%@/%@", cachePath, p];
        if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
            [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
        }
        NSLog(@"%@", p);
    }
    for (NSString *p in uploadFiles) {
        NSString *path = [NSString stringWithFormat:@"%@/%@", documentsDirectory, p];
        if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
            [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
        }
        NSLog(@"文件 %@", p);
    }
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    for (NSString *path in self.userDefaultKeys) {
        [userDefaults setBool:NO forKey:path];
    }
    NSLog(@"清除缓存");
    
//    // 把lastReplyID 设为 0 当清除缓存的时候
//    [userDefaults setObject:@"0" forKey:@"lastReplyID"];
//    
//    // 清除消息缓存
//    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingString:@"Message"];
//    NSFileManager *fileManager = [[NSFileManager alloc]init];
//    [fileManager removeItemAtPath:path error:nil];
    // 清除缓存的时候发个通知 改变所有下载状态
    [[NSNotificationCenter defaultCenter] postNotificationName:@"CHANGEALLSTATUS" object:nil];
    
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingString:@"Message"];
    NSFileManager *fileManager = [[NSFileManager alloc]init];
    [fileManager removeItemAtPath:path error:nil];
    
    
}
- (void)dismiss{
    [SVProgressHUD dismiss];
}
#pragma mark - 回到登录页面
- (void)goBackLoginPage{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        UIStoryboard *login = [UIStoryboard storyboardWithName:@"DALogin" bundle:nil];
        self.view.window.rootViewController = login.instantiateInitialViewController;
        [SVProgressHUD dismiss];
    });

}

- (void)changeWordFinished:(NSDictionary *)dictionary{
    self.personalInformation.userName = [dictionary objectForKey:@"userName"];
    self.personalInformation.userSign = [dictionary objectForKey:@"userSign"];
    [self.tableView reloadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidDisappear:(BOOL)animated{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"REFRESH" object:self];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
